package org.example.versii.server;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.example.versii.annotation.RpcService;
import org.example.versii.channel.impl.ChannelFactory;
import org.example.versii.register.IRegistry;
import org.example.versii.util.NetworkAddressUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * @author mojito
 * @Classname RpcServer
 * @Description TODO
 * @Date 2020/7/21 下午11:02
 **/
@Component("rpcServer")
@PropertySource(value = {"classpath:application.properties"})
@Slf4j
public class RpcServer implements ApplicationContextAware {

    @Value("${rpc.server.port}")
    private int port;

    @Value("${rpc.server.channel}")
    private String channelType;

    @Autowired
    private ChannelFactory factory;

    @Autowired
    private IRegistry registry;


    @PostConstruct
    public void bootServer() {
        log.info("server ready to start");
        factory.getChannel(channelType).process(port);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(RpcService.class);
        log.info("publishing service");
        if (MapUtils.isNotEmpty(beans)) {
            beans.values().forEach(bean -> {
                Class<?> value = bean.getClass().getAnnotation(RpcService.class).value();
                //本地注册
                ServiceMap.registryService(value.getName(), bean);
                //注册中心
                registry.registry(value.getName(), NetworkAddressUtils.getLocalIp() + ":" + port);
            });
        }
    }
}
